import { useEffect, useState } from "react";
import { message } from "antd";
import { addUserSignInUsingPost } from "@/api/userController";
import { useSelector } from "react-redux";
import type { RootState } from "@/stores";

/**
 * 添加用户签到记录钩子
 */
const useAddUserSignInRecord = () => {
    //签到状态
    const [loading, setLoading] = useState(false);
    // 全局登录信息
    const loginUser = useSelector((state: RootState) => state.loginUser);

    // 请求后端执行签到
    const doFetch = async () => {
        setLoading(true);
        try {
            await addUserSignInUsingPost();
        } catch (e) {
            // @ts-ignore
            message.error("添加刷题签到记录失败，" + e.message);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        // 仅在用户已登录时执行签到
        // 未登录用户不应触发接口，以免触发 401 重定向
        const isLoggedIn = !!loginUser?.id && loginUser.userRole && loginUser.userRole !== "not_login";
        if (isLoggedIn) {
            doFetch();
        }
    }, [loginUser?.id, loginUser?.userRole]);

    return { loading };
};

export default useAddUserSignInRecord;
